/*
 * @Author: Await
 * @Date: 2025-05-10 09:25:00
 * @LastEditors: Await
 * @LastEditTime: 2025-05-12 15:09:07
 * @Description: 3D图表工具函数
 */

import { logDebug } from './commonUtils';

// 3D图表类型列表
const CHART_3D_TYPES = [
  'bar3D',
  'scatter3D',
  'line3D',
  'surface',
  'map3D',
  'geo3D',
  'globe',
  'scatterGL',
  'graphGL',
  'flowGL'
];

/**
 * 判断是否为3D图表类型
 * @param chartType 图表类型
 * @returns 是否为3D图表
 */
export const is3DChartType = (chartType: string): boolean => {
  return CHART_3D_TYPES.includes(chartType);
};

/**
 * 确保EChartsGL库已加载
 * 由于使用静态导入，此函数仅用于兼容性目的
 * @param forceReload 不再使用
 * @returns Promise，始终解析为true
 */
export const ensureEChartsGLLoaded = (): Promise<boolean> => {
  // 由于使用静态导入，我们假设GL库始终可用
  return Promise.resolve(true);
};

/**
 * 强制重新加载GL库
 * 由于使用了静态导入，此函数现在只触发必要的事件，不再执行实际的重载
 * @param forceReloadEvent 是否触发加载完成事件
 * @returns Promise，始终解析为成功
 */
export const forceReloadGLLibrary = (forceReloadEvent: boolean = true): Promise<boolean> => {
  console.log('[3D] 使用静态导入，无需强制重载GL库，仅触发事件');

  return new Promise<boolean>((resolve) => {
    if (forceReloadEvent) {
      try {
        // 触发标准事件
        const event = new CustomEvent('echarts-gl-loaded', {
          detail: {
            timestamp: Date.now(),
            forced: false,
            fromStatic: true,
            componentCount: (window as any).echarts?.gl ?
              Object.keys((window as any).echarts.gl).length : 0
          }
        });
        window.dispatchEvent(event);

        // 触发包含更多信息的重载完成事件
        const reloadEvent = new CustomEvent('echarts-gl-reloaded', {
          detail: {
            timestamp: Date.now(),
            fromStatic: true,
            componentCount: (window as any).echarts?.gl ?
              Object.keys((window as any).echarts.gl).length : 0,
            components: (window as any).echarts?.gl ?
              Object.keys((window as any).echarts.gl) : []
          }
        });
        window.dispatchEvent(reloadEvent);

        // 触发图表重建事件
        setTimeout(() => {
          const resetEvent = new CustomEvent('echarts-gl-reset', {
            detail: { timestamp: Date.now() }
          });
          window.dispatchEvent(resetEvent);
        }, 50);
      } catch (err) {
        console.error('[3D] 触发事件失败:', err);
      }
    }

    // 始终返回成功
    resolve(true);
  });
};

/**
 * 处理3D图表配置
 * 为3D图表添加必要的特定配置
 * @param config 原始配置
 * @returns 处理后的3D图表配置
 */
export const process3DChartConfig = (config: any): any => {
  if (!config) return config;

  // 减少详细日志，仅在非生产环境下输出
  const isDevelopment = window.location.hostname === 'localhost' ||
    window.location.hostname === '127.0.0.1' ||
    window.location.hostname.includes('192.168.');

  if (isDevelopment) {
    console.log('[3D] 处理3D图表配置开始:', {
      type: config.type,
      hasGrid3D: !!config.grid3D,
      hasSeries: !!config.series,
      seriesLength: config.series ? (Array.isArray(config.series) ? config.series.length : 1) : 0
    });
  }

  // 创建配置副本以避免修改原始对象
  const processed3DConfig = { ...config };

  // 根据图表类型添加特定配置
  const chartType = processed3DConfig.type || '';

  // 确保所有3D图表配置都有series且具有正确的type
  if (!processed3DConfig.series) {
    processed3DConfig.series = [{
      type: chartType,
      data: [],
      name: '3D数据系列'
    }];
  } else if (!Array.isArray(processed3DConfig.series)) {
    processed3DConfig.series = [processed3DConfig.series];
  }

  // 检查是否已经有完整的3D配置，如果有则跳过部分处理
  const hasCompleteGrid3D = processed3DConfig.grid3D &&
    processed3DConfig.xAxis3D &&
    processed3DConfig.yAxis3D &&
    processed3DConfig.zAxis3D;

  // 如果配置不完整，添加必要配置
  if (!hasCompleteGrid3D) {
    // 确保每个series都有正确的type
    processed3DConfig.series.forEach((series: any, index: number) => {
      if (!series.type) {
        series.type = chartType;
      }

      // 确保数据格式正确
      if (series.data && Array.isArray(series.data)) {
        // 对于3D图表，确保数据格式正确
        if (chartType === 'bar3D' || chartType === 'scatter3D' || chartType === 'line3D') {
          series.data = series.data.map((item: any) => {
            // 如果是数组形式，确保至少有3个元素 [x, y, z]
            if (Array.isArray(item) && item.length < 3) {
              const result = [...item];
              while (result.length < 3) result.push(0);
              return result;
            }
            return item;
          });
        }
      }

      // 为所有3D系列添加默认的材质和光照配置
      if (chartType.includes('3D') || chartType.includes('GL')) {
        // 添加默认材质
        if (!series.itemStyle) {
          series.itemStyle = {};
        }

        // 确保材质可以响应光照，但不覆盖已存在的值
        if (!series.itemStyle.opacity) {
          series.itemStyle.opacity = 0.8;
        }

        // 添加特定高光效果
        if (!series.itemStyle.emphasis) {
          series.itemStyle.emphasis = {
            opacity: 1
          };
        }

        // 为bar3D特别设置柱体材质
        if (chartType === 'bar3D') {
          // 确保材质正确显示
          series.shading = series.shading || 'realistic';

          // 应用更好的光照反射，但不覆盖用户设置
          if (!series.itemStyle.metalness && series.itemStyle.metalness !== 0) {
            series.itemStyle.metalness = 0.4;
          }
          if (!series.itemStyle.roughness && series.itemStyle.roughness !== 0) {
            series.itemStyle.roughness = 0.5;
          }
        }
      }
    });

    // 根据3D图表类型添加特定配置
    switch (chartType) {
      case 'bar3D':
        // 为3D柱状图添加默认设置，但不覆盖已存在的设置
        processed3DConfig.grid3D = {
          boxWidth: 200,
          boxHeight: 100,
          boxDepth: 80,
          viewControl: {
            autoRotate: false,
            rotateSensitivity: 5,
            distance: 150,
            alpha: 20, // 视角alpha角度
            beta: 40   // 视角beta角度
          },
          // 启用环境光遮蔽以增强3D效果
          environment: '#fff',
          // 显示坐标轴
          show: true,
          axisLine: {
            show: true
          },
          axisPointer: {
            show: true
          },
          // 使用现有grid3D配置覆盖默认值
          ...(processed3DConfig.grid3D || {})
        };

        // 确保坐标轴设置正确
        processed3DConfig.xAxis3D = {
          type: 'category',
          axisLine: {
            show: true
          },
          axisLabel: {
            show: true
          },
          ...(processed3DConfig.xAxis3D || {})
        };

        processed3DConfig.yAxis3D = {
          type: 'category',
          axisLine: {
            show: true
          },
          axisLabel: {
            show: true
          },
          ...(processed3DConfig.yAxis3D || {})
        };

        processed3DConfig.zAxis3D = {
          type: 'value',
          axisLine: {
            show: true
          },
          axisLabel: {
            show: true
          },
          ...(processed3DConfig.zAxis3D || {})
        };

        if (isDevelopment) {
          console.log('[3D] bar3D最终配置:', {
            hasGrid3D: !!processed3DConfig.grid3D,
            grid3DProps: Object.keys(processed3DConfig.grid3D || {}),
            hasXAxis3D: !!processed3DConfig.xAxis3D,
            hasYAxis3D: !!processed3DConfig.yAxis3D,
            hasZAxis3D: !!processed3DConfig.zAxis3D
          });
        }
        break;

      case 'scatter3D':
      case 'line3D':
        // 为3D散点图和3D线图添加默认设置
        processed3DConfig.grid3D = processed3DConfig.grid3D || {};
        processed3DConfig.grid3D = {
          viewControl: {
            projection: 'perspective',
            autoRotate: false
          },
          ...processed3DConfig.grid3D
        };

        // 确保坐标轴设置正确
        processed3DConfig.xAxis3D = processed3DConfig.xAxis3D || { type: 'value' };
        processed3DConfig.yAxis3D = processed3DConfig.yAxis3D || { type: 'value' };
        processed3DConfig.zAxis3D = processed3DConfig.zAxis3D || { type: 'value' };
        break;

      case 'surface':
        // 为3D曲面图添加默认设置
        processed3DConfig.grid3D = processed3DConfig.grid3D || {};
        processed3DConfig.grid3D = {
          viewControl: {
            autoRotate: false,
            zoomSensitivity: 2
          },
          ...processed3DConfig.grid3D
        };

        // 确保坐标轴设置正确
        processed3DConfig.xAxis3D = processed3DConfig.xAxis3D || { type: 'value' };
        processed3DConfig.yAxis3D = processed3DConfig.yAxis3D || { type: 'value' };
        processed3DConfig.zAxis3D = processed3DConfig.zAxis3D || { type: 'value' };
        break;

      case 'map3D':
      case 'geo3D':
      case 'globe':
        // 为地理3D图添加默认设置
        if (!processed3DConfig.geo3D && !processed3DConfig.globe) {
          processed3DConfig.geo3D = {
            viewControl: {
              autoRotate: false
            }
          };
        }
        break;

      case 'scatterGL':
      case 'graphGL':
      case 'flowGL':
        // 为GL系列图表添加默认设置
        break;

      default:
        // 不是已知的3D图表类型，可能需要额外处理
        break;
    }
  }

  // 确保光照配置存在并设置合理的值，但不覆盖已有设置
  if (!processed3DConfig.light) {
    processed3DConfig.light = {
      main: {
        // 加强主光源强度，解决黑色渲染问题
        intensity: 1.5,
        // 调整光源角度，从不同方向照射以避免阴影过重
        alpha: 30,
        beta: 40,
        shadow: true,
        shadowQuality: 'high'
      },
      ambient: {
        // 加强环境光照强度，减少阴影过重问题
        intensity: 0.5
      },
      // 添加辅助光源，从另一方向照亮场景
      ambientCubemap: {
        texture: null,
        exposure: 1,
        diffuseIntensity: 0.8
      }
    };
  } else {
    // 合并用户配置和默认配置
    if (!processed3DConfig.light.main) {
      processed3DConfig.light.main = {
        intensity: 1.5,
        alpha: 30,
        beta: 40,
        shadow: true,
        shadowQuality: 'high'
      };
    }
    if (!processed3DConfig.light.ambient) {
      processed3DConfig.light.ambient = {
        intensity: 0.5
      };
    }
  }

  // 减少详细日志，仅在非生产环境下输出
  if (isDevelopment) {
    console.log(`[3D] 3D图表配置处理完成: ${chartType}`, {
      hasGrid3D: !!processed3DConfig.grid3D,
      hasAxis3D: {
        x: !!processed3DConfig.xAxis3D,
        y: !!processed3DConfig.yAxis3D,
        z: !!processed3DConfig.zAxis3D
      },
      hasLight: !!processed3DConfig.light,
      seriesCount: processed3DConfig.series ? processed3DConfig.series.length : 0
    });
  }

  logDebug(`[DEBUG] 3D图表配置处理完成: ${chartType}`);
  return processed3DConfig;
};
